# models/base.py
"""
Author: didiplus
Description: 数据库模型基类定义
Date: 2025-08-20 20:37:07
LastEditors: didiplus
LastEditTime: 2025-08-20 20:37:08
FilePath: /WeChatBot/app/models/base.py
Version: 1.0
"""
from sqlalchemy import Column, Integer, DateTime, Boolean, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import declared_attr
from datetime import datetime

Base = declarative_base()

class BaseModel(Base):
    """
    所有模型的基类，包含公共字段
    """
    __abstract__ = True
    
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()
    
    #: 主键ID
    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    
    #: 创建时间
    created_at = Column(DateTime, default=func.now(), nullable=False, comment="创建时间")
    
    #: 更新时间
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")
    
    #: 是否激活
    is_active = Column(Boolean, default=True, nullable=False, comment="是否激活")
    
    def to_dict(self):
        """
        将模型对象转换为字典格式
        自动处理所有列，包括子类中定义的列
        特殊处理日期时间字段，转换为ISO格式字符串
        """
        result = {}
        # 遍历所有列
        for column in self.__table__.columns:
            value = getattr(self, column.name)
            # 特殊处理日期时间字段
            if isinstance(value, datetime):
                result[column.name] = value.isoformat() if value else None
            else:
                result[column.name] = value
        return result